package com.autumn.platform.web.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;

import com.autumn.platform.core.logger.Logs;
import com.autumn.platform.web.jsonbody.JsonBodySupport;
import com.autumn.platform.web.resulthandler.context.HandlerMethodContext;
import com.autumn.platform.web.resulthandler.context.HandlerMethodContextHolder;
import com.autumn.platform.web.resulthandler.context.impl.HandlerMethodContextImpl;

public class ControllerAspect {

    /**
     * Web控制层AOP
     * 
     * @param point 节点
     * @return 原方法返回值
     */
    public Object doAspect(ProceedingJoinPoint point) throws Throwable {
        long start = System.currentTimeMillis();
        HandlerMethodContext result = null;
        Method method = AopHelp.getPointMethod(point);
        Object[] args = point.getArgs();
        try {
            Logs.debug("enter into the class and call the method: " + point.getSignature());
            Object rs = point.proceed();
            Logs.debug("the method has executed success in " + (System.currentTimeMillis() - start) + " ms, exit method: " + point.getSignature());
            result = new HandlerMethodContextImpl(args, rs, null, start, System.currentTimeMillis());
            return rs;
        } catch (Throwable e) {
            Logs.error("the method has occured exception, execute failure and exit after " + (System.currentTimeMillis() - start) + " ms, method: " + point.getSignature() + ", message: " + e.getMessage());
            result = new HandlerMethodContextImpl(args, null, e, start, System.currentTimeMillis());
            throw e;
        } finally {
            HandlerMethodContextHolder.setHandlerMethodContext(result);
            JsonBodySupport.setJsonBody(method);
        }
    }
}
